<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    * { margin: 0; padding: 0; }
    img { float: left; }
    table { width: 600px; }
    th { text-align: left }
    thead th { border-bottom: 1px solid #ddd; padding: 5px 0; }
  </style>
</head>
<body>
<h1>Unpack Chunks of a PNG</h1>
<p>The PNG shown left gets read by a stream and then transformed to a stream of PNG chunks. By this, the PNG can be processed before the fetch is complete.</p>
<img src="png-logo.png" width="640" height="480">
<table>
  <thead>
  <tr>
    <th width="300">Stream</th>
    <th>Chunk No.</th>
    <th>Sent chunk type</th>
  </tr>
  </thead>
  <tbody>

  </tbody>
</table>
<script src="crc32.js"></script>
<script src="png-chunks.js"></script>
<script src="png-transform-stream.js"></script>
<script type="application/javascript">
  const tbody = document.getElementsByTagName('tbody')[0];

  class LogStreamSink {
    /**
     * @param {string} name
     */
    constructor(name) {
      this.name = name;
      this.counter = 0;
    }

    /**
     * Called when a chunk is written to the log.
     */
    write(chunk) {
      this.counter += 1;
      console.log('Chunk %d of %s: %o', this.counter, this.name, chunk);

      this.createRow(this.name, this.counter, chunk.constructor.name);
    }

    /**
     * Called when the stream is closed.
     */
    close() {
      this.createRow(this.name, this.counter, 'Closed');
    }

    /**
     * Creates a row in the table.
     *
     * @param {string} heading
     * @param {string} col1
     * @param {string} col2
     */
    createRow(heading, col1, col2) {
      const tr = document.createElement('tr');
      tbody.appendChild(tr);
      const th = document.createElement('th');
      th.appendChild(document.createTextNode(heading));
      tr.appendChild(th);
      const tdCounter = document.createElement('td');
      tdCounter.appendChild(document.createTextNode(col1));
      tr.appendChild(tdCounter);
      const tdChunk = document.createElement('td');
      tdChunk.appendChild(document.createTextNode(col2));
      tr.appendChild(tdChunk);
    }
  }

  function logReadableStream(name, rs) {
    const [rs1, rs2] = rs.tee();

    rs2.pipeTo(new WritableStream(new LogStreamSink(name))).catch(console.error);

    return rs1;
  }


  // Fetch the original image
  fetch('png-logo.png')
  // Retrieve its body as ReadableStream
  .then(response => response.body)
  // Log each fetched Uint8Array chunk
  .then(rs => logReadableStream('Fetch Response Stream', rs))
  // Transform to a PNG chunk stream
  .then(rs => rs.pipeThrough(new PNGTransformStream()))
  // Log each transformed PNG chunk
  .then(rs => logReadableStream('PNG Chunk Stream', rs))

</script>
</body>
</html>
